import { RouteRecordRaw, createWebHistory, createRouter, RouteMeta } from "vue-router";
import { constructRouteMenu } from '@/utils/project'
import Layout from '@/layout/index.vue'
import AbnormalPage from '@/views/404.vue'

const pages = import.meta.glob('../views/**/page.ts', { eager: true, import: 'default' });
const comps = import.meta.glob('../views/**/index.vue'); // 不通过这种方式引入vue文件，会导致打包后动态引入失败

// 公共路由(约定大于配置，对代码的动态生成)
const importRoutes: Array<RouteRecordRaw> = Object.entries(pages).map(([path, meta]) => {
    const compPath = path.replace('page.ts', 'index.vue')
    path = path.replace('../views', '').replace('/page.ts', '') || '/index';
    const name = path.split('/').filter(Boolean).join('-') || 'index'
    const tempMap: RouteMeta = meta as RouteMeta
    console.log(comps[compPath]);
    
    return { path, name, component: comps[compPath], meta: tempMap }
})

// 动态路由，基于用户权限动态去加载
const dynamicRoutes: Array<RouteRecordRaw> = []

// 树形路由
export const treeRoutes: Array<RouteRecordRaw> = Array.isArray(dynamicRoutes) && dynamicRoutes.length > 0 ? dynamicRoutes : constructRouteMenu(importRoutes)

// 静态路由
const constantRoutes: Array<RouteRecordRaw> = [
    {
        "path": "/",
        "component": Layout,
        "redirect": "/index",
        "children": [
            {
                "path": "/index",
                "name": "index",
                "component": comps['../views/index.vue'],
                "meta": {
                    "title": "首页",
                    "keepAlive": false, // 需要被缓存
                    "noCache": true
                },
            }
        ]
    },
    {
        "path": "/login",
        "component": comps['../views/login/index.vue'],
        "name": "login",
        "meta": {
            "title": "登录",
        }
    }
]

const finalRouters: Array<RouteRecordRaw> = [...constantRoutes, ...treeRoutes, { path: "/:pathMatch(.*)", component: AbnormalPage }]

const router = createRouter({
    history: createWebHistory(import.meta.env.VITE_APP_BASE_URL),
    routes: finalRouters,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0 }
        }
    },
});

export default router;